﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Linq;
using Pipra.Math;
using Pipra.Math.Geometry;

namespace Pipra.Gis.Transformation
{
    /// <summary>
    /// An abridged molodensky transformation.
    /// </summary>
    public class AbridgedMolodenskyTransformation : ITransformation<LatLonH>
    {

        private static readonly double SinOne = System.Math.Sin(1);

        protected readonly Vector3 D;
        protected readonly double Da;
        protected readonly double SeSq;
        protected readonly double Sadfsfda;
        protected readonly double OneMinusESqsaSinOne;
        protected readonly double SaSinOne;

        protected readonly ISpheroid<double> SourceSpheroid;
        protected readonly ISpheroid<double> TargetSpheroid;

        /// <summary>
        /// Constructs an abridged molodensky transformation.
        /// </summary>
        /// <param name="translation">The amount to translate.</param>
        /// <param name="sourceSpheroid">The source CRS spheroid.</param>
        /// <param name="targetSpheroid">The destination CRS spheroid.</param>
        public AbridgedMolodenskyTransformation(
            ICoordinateTriple<double> translation,
            ISpheroid<double> sourceSpheroid,
            ISpheroid<double> targetSpheroid
        )
        {
            SourceSpheroid = sourceSpheroid;
            TargetSpheroid = targetSpheroid;
            D = new Vector3(translation);
            double sf = sourceSpheroid.F;
            double tf = targetSpheroid.F;
            double df = tf - sf;
            double sa = sourceSpheroid.A;
            double ta = targetSpheroid.A;
            Da = ta - sa;
            SeSq = sourceSpheroid.ESquared;
            Sadfsfda = (sa * df) + (sf * Da);
            SaSinOne = sa * SinOne;
            OneMinusESqsaSinOne = SaSinOne * (1.0 - SeSq);
            if (0 == OneMinusESqsaSinOne || 0 == SaSinOne)
            {
                throw new ArgumentException("Invalid spheroid.", "sourceSpheroid");
            }
        }

        public LatLonH TransformValue(LatLonH coord)
        {
            double sinLats = System.Math.Sin(coord.Lat);
            double sinLatsSq = sinLats * sinLats;
            double cosLats = System.Math.Cos(coord.Lat);
            double sinLons = System.Math.Sin(coord.Lon);
            double cosLons = System.Math.Cos(coord.Lon);
            double c = 1.0 - (SeSq * sinLatsSq);
            double cSq = System.Math.Sqrt(c);
            double dxdy = (D.X * cosLons) + (D.Y * sinLons);
            return new LatLonH(
                coord.Lat + (
                    (
                        (
                            (D.Z * cosLats)
                            + (Sadfsfda * System.Math.Sin(2.0 * coord.Lat))
                            - (sinLats * dxdy)
                        )
                        * c * cSq
                    )
                    / OneMinusESqsaSinOne
                ),
                coord.Lon + (
                    (
                        ((D.Y * cosLons) - (D.X * sinLons))
                        * cSq
                    )
                    / (cosLats * SaSinOne)
                ),
                coord.Height + (
                    +(cosLats * dxdy)
                    + (D.Z * sinLats)
                    + (Sadfsfda * sinLatsSq)
                    - Da
                )
            );
        }

        public void TransformValues(LatLonH[] values)
        {
            for (int i = 0; i < values.Length; i++)
            {
                TransformValue(ref values[i]);
            }
        }

        [CLSCompliant(false)]
        public void TransformValue(ref LatLonH value)
        {
            value = TransformValue(value);
        }

        public ITransformation<LatLonH> GetInverse()
        {
            return new AbridgedMolodenskyTransformation(D.GetNegative(), TargetSpheroid, SourceSpheroid);
        }

        public bool HasInverse
        {
            get { return (0 != TargetSpheroid.A && 0 != (1.0 - TargetSpheroid.ESquared)); }
        }

        ITransformation ITransformation.GetInverse()
        {
            return GetInverse();
        }

        ITransformation<LatLonH, LatLonH> ITransformation<LatLonH, LatLonH>.GetInverse()
        {
            return GetInverse();
        }

        public IEnumerable<LatLonH> TransformValues(IEnumerable<LatLonH> values)
        {
            return values.Select(TransformValue);
        }


    }
}
